import Vue from "vue"

// 获取初始化默认值
function getDefaultState() {
	// 没有token 则返回空
	if (!uni.getStorageSync('chuchujie-token')) {
		uni.setStorageSync('chuchujie-userInfo', '') // 清空用户信息
		uni.setStorageSync('chuchujie-token', '') // 清空用户信息
		return {
			token: '',
			userInfo: ''
		}
	}

	// 操作时效超出7天 返回空
	const tokenDate = uni.getStorageSync('chuchujie-token').date // token保存时间
	if ((new Date().getTime() - tokenDate) / (24 * 3600 * 1000) >= 7) { // 大于或等于7天
		uni.setStorageSync('chuchujie-userInfo', '') // 清空用户信息
		uni.setStorageSync('chuchujie-token', '') // 清空用户信息
		return {
			token: '',
			userInfo: ''
		}
	}

	// token未过期(继续保持登录状态)
	return {
		token: uni.getStorageSync('chuchujie-token'),
		userInfo: uni.getStorageSync('chuchujie-userInfo')
	}
}

const state = getDefaultState()

const mutations = {
	// 存储token到vuex和缓存之中
	SET_TOKEN: (state, data) => {
		if (data) {
			const date = new Date().getTime()
		  state.token = { date, value: data }
		  uni.setStorageSync('chuchujie-token', { date, value: data })
			uni.setStorageSync('chuchujie-refreshTokenTime', date) // 更新token上次刷新时间
		} else { // 退出登录
			state.token = ''
		  uni.setStorageSync('chuchujie-token', '')
			uni.setStorageSync('chuchujie-userInfo', '') // 清空用户信息
		}
	},
	SET_USERINFO: (state, data) => {
			state.userInfo = data
			uni.setStorageSync('chuchujie-userInfo', data)
	}
}
const actions = {
	// 用户登陆
	Login({ commit }, data) {
		return new Promise((resolve, resject) => {
			Vue.prototype.$user.userLogin(data).then(({ code, data }) => {
				if (code === 0) {
					commit('SET_TOKEN', data)
					resolve(code)
				} else {
					resolve(code)
				}
			}).catch(error => {
				reject(error)
			})
		})
	},
	// 获取用户信息
	GetInfo({ commit, dispatch }) {
		return new Promise((resolve, reject) => {
			Vue.prototype.$user.userGetInfo().then(({ code, data }) => {
				if (code === 0) {
					commit('SET_USERINFO', data)
					// 调用其他模块方法
					dispatch('chat/ChatGroup', data.userId, { root: true })
					resolve(code)
				}
			})
		})
	},
	// 退出登录
	Loginout({ commit }) {
		return new Promise(async(resolve) => {
			commit('SET_TOKEN', '')
			commit('SET_USERINFO', '')
			uni.$emit('closeWebsocket')
			resolve(0)
		})
	},
	// 刷新token
	// 这里分两种情况：
	// 1、微信小程序检查登录状态，未登陆再刷新
	// 2、非微信小程序正常刷新token
	RefreshToken({ commit }) {
		return new Promise(async(resolve) => {
			// #ifdef MP-WEIXIN
			uni.checkSession({
				fail: () => { // 调用失败说明 session_key 已过期
					Vue.prototype.$user.userRefreshToken().then(({ code, data }) => {
						if (code === 0) {
							commit('SET_TOKEN', data)
							resolve()
						}
					})
				}
			})
			// #endif
			// #ifndef MP-WEIXIN
      Vue.prototype.$user.userRefreshToken().then(({ code, data }) => {
				if (code === 0) {
					commit('SET_TOKEN', data)
					resolve()
				}
			})
      // #endif
			
		})
	},
		// 微信登录
		wxLogin({ commit }, { encryptedData, iv, phone }) {
			return new Promise(async(resolve) => {
				uni.login({
					provider: 'weixin',
					success: async ({ code, errMsg }) => {
						if (errMsg === 'login:ok') {
							// 调用接口传入code，返回token
							const { data: token } = await Vue.prototype.$user.userWxLogin({	
								code,
								encryptedData: encryptedData ? encryptedData : undefined,
								iv: iv ? iv : undefined,
								phone: phone ? phone : undefined
							})
							if (token) { // 返回了token
								resolve(0)
								commit('SET_TOKEN', token)
							} else { // 未返回
								resolve(-1)
							}
						}
					}
				})
			})
		}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}
